package net.wantongtech.xa.uploadbasicinfo.service;

import com.wtkj.vo.dzzf.base.xxdl.InteractionOrgMsgReceive;
import lombok.extern.slf4j.Slf4j;
import net.wantongtech.xa.uploadbasicinfo.config.FastDFSConfig;
import net.wantongtech.xa.uploadbasicinfo.dao.DealWithMissingTransPackageDao;
import org.apache.commons.lang3.StringUtils;
import org.csource.client.FastDFSClient;
import org.csource.common.MyException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

/**
 * 处理硬盘缺失文件服务实现
 *
 * @author MaShibo
 * 日期 :  2020/2/3
 */
@Slf4j
@Service
public class DealWithDiskMissingTransPackageService {

    @Resource
    private DealWithMissingTransPackageDao dealWithMissingTransPackageDao;

    @Resource
    private FastDFSConfig fastDFSConfig;

    public void process() {
        List<String> receiveIdList = dealWithMissingTransPackageDao.queryDiskMissingTransPackageReceiveId();
        log.info("共查询出{}条待处理接收表数据", receiveIdList.size());
        if (receiveIdList.isEmpty()) {
            log.info("结束执行");
            return;
        }
        receiveIdList.forEach(receiveId -> {
            try {
                processSingle(receiveId);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        });
    }

    private void processSingle(String receiveId) throws MyException {
        InteractionOrgMsgReceive ormObj = new InteractionOrgMsgReceive();
        ormObj.setListID(receiveId);
        InteractionOrgMsgReceive receiveMsg = (InteractionOrgMsgReceive) dealWithMissingTransPackageDao.queryObject(ormObj);
        if (receiveMsg == null) {
            log.info("ListId为：{}对应接收表记录不存在", receiveId);
            return;
        }
        String storePath = receiveMsg.getStorePath();
        File targetFile = new File(storePath);
        if (!targetFile.exists()) {
            log.info("对应文件：{}，不存在，结束处理", storePath);
            return;
        }
        fastDFSConfig.init();
        String url = FastDFSClient.uploadFile(targetFile);
        log.info("文件：{}上传FastDFS成功，返回url：{}", targetFile, url);
        if (StringUtils.isNotBlank(url)) {
            ormObj.setStoreFlag(InteractionOrgMsgReceive.STORE_FLAG_DFS);
            ormObj.setStorePath(url);
            dealWithMissingTransPackageDao.updateObject(ormObj);

            try {
                Files.delete(Paths.get(targetFile.toURI()));
            } catch (IOException e) {
                log.info("文件：{}删除失败，错误：{}", targetFile, e.getMessage());
            }
        }
    }
}
